package com.ellricky.newtv

import android.content.pm.ActivityInfo
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.andr.common.ui.activity.BaseActivity
import com.andr.common.ui.mvp.BasePresenter
import com.angcyo.tablayout.DslTabLayout
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.newtv.ClassInfo
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewEListCallback
import com.ellricky.baselib.util.jump
import com.ellricky.newtv.adapter.CourseFileAdapter
import com.ellricky.newtv.adapter.TYPE_NORMAL
import com.ellricky.newtv.bean.TvCourseFile
import com.ellricky.newtv.bean.TvCourseStage
import com.ellricky.newtv.const.TvConst
import com.ellricky.newtv.utils.CacheToken
import kotlinx.android.synthetic.main.activity_new_tv_course_file.*

class NewTvCourseFileActivity : BaseActivity<Void, BasePresenter<Void>>() {

    private val courseId: String by lazy {
        intent.getStringExtra(TvConst.KEY_ID) ?: ""
    }
    private val courseFileAdapter by lazy {
        CourseFileAdapter(TYPE_NORMAL)
    }

    private var tvBindClass: ClassInfo? = null

    override fun setOrientation() {
        this.requestedOrientation =
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }

    override fun getContentLayout(): Int {
        return R.layout.activity_new_tv_course_file
    }

    override fun initUIView() {
        CacheToken.verifyToken()
        tvBindClass = LocalCacheUtil.readTvClassInfo()
        tv_back.setOnClickListener(this)
        tv_bind_class.setOnClickListener(this)
        tabLayout.setTabLayoutConfig {
            onSelectItemView = { itemView: View, index: Int, select: Boolean, fromUser: Boolean ->
                if (select) {
                    val id = itemView.tag.toString()
                    loadCourseList(id)
                }
                false
            }
            tabSelectColor = ContextCompat.getColor(this@NewTvCourseFileActivity, R.color.blue)
            tabDeselectColor = ContextCompat.getColor(this@NewTvCourseFileActivity, R.color.white)
        }
        initRv()
        fetchData()
    }

    private fun fetchData() {
        loadCourseState()
    }

    override fun onResume() {
        super.onResume()
        tvBindClass = LocalCacheUtil.readTvClassInfo()
        if (tvBindClass != null) {
            tv_bind_class.text = tvBindClass?.name
        }
    }

    private fun createTextView(index: Int, text: String, id: String): TextView {
        return TextView(this).also {
            it.textSize = 18f
            it.text = text
            it.tag = id
            it.setTextColor(R.drawable.selector_text_color)
            if (index != 0) {
                val params = DslTabLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                )
                params.marginStart = resources.getDimension(R.dimen.dp_30).toInt()
                it.layoutParams = params
            }
        }
    }

    private fun loadCourseState() {
        val url = EAppUtil.getTvApiHost()
        val paramMap = mutableMapOf(
            "action" to "courseStageList",
            "course_id" to courseId,
            "eid" to LocalCacheUtil.getTvUid()
        )
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<TvCourseStage>(this, false) {
                override fun onSuccess(data: MutableList<TvCourseStage>, msg: String?) {
                    data.forEachIndexed { index, tvCourseStage ->
                        if (index == 0) {
                            loadCourseList(tvCourseStage.stage_id)
                        }
                        tabLayout.addView(
                            createTextView(
                                index,
                                tvCourseStage.stage_name,
                                tvCourseStage.stage_id
                            )
                        )
                    }
                }
            }, this)
    }

    fun loadCourseList(courseStageId: String) {
        val url = EAppUtil.getTvApiHost()
        val paramMap = mutableMapOf(
            "action" to "courseWareList",
            "course_type_id" to courseId,
            "course_stage_id" to courseStageId,
            "eid" to LocalCacheUtil.getTvUid()
        )
        if (tvBindClass != null) {
            paramMap["class_id"] = tvBindClass?.id
        }
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<TvCourseFile>(this, false) {
                override fun onSuccess(data: MutableList<TvCourseFile>, msg: String?) {
                    courseFileAdapter.setList(data)
                }

                override fun onErrorCode(code: String?, msg: String?) {
                    super.onErrorCode(code, msg)
                    courseFileAdapter.setList(arrayListOf())
                }
            }, this)
    }

    override fun onClickView(v: View) {
        super.onClickView(v)
        when (v.id) {
            R.id.tv_back -> finish()
            R.id.tv_bind_class -> {
                jump<NewTvBindClassActivity> { }
            }
        }
    }

    private fun initRv() {
        rv_course_file.layoutManager = GridLayoutManager(this, 4)
        rv_course_file.adapter = courseFileAdapter
        rv_course_file.addItemDecoration(GridItemDecoration2(4, 20, 20))
        courseFileAdapter.addChildClickViewIds(R.id.tv_contact, R.id.iv_cover)
        courseFileAdapter.setOnItemChildClickListener { _,
                                                        view,
                                                        position ->

            val data = courseFileAdapter.data[position]

            when (view.id) {
                R.id.tv_contact -> {
                    jump<NewTvConnectActivity>()
                }
                R.id.iv_cover -> {
                    if (!data.ware_ppt.isNullOrEmpty()) {
                        jump<NewTvFileDetailActivity> {
                            putStringArrayListExtra(TvConst.KEY_IMAGE, data.ware_ppt)
                            putExtra(TvConst.KEY_TYPE, data.ware_type)
                            putExtra(TvConst.KEY_ID, data.ware_id)
                        }
                    } else {
                        Toast.makeText(this, "暂无数据", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalCacheUtil.saveTvBindClass(null)
    }
}